<template>
	<div class="image-drag">
		<div class="switch-view">
			<el-button type="primary" size="small" @click="fileClick" @drop="drop($event)" @dragenter="dragenter($event)"
			 @dragover="dragover($event)">上传图片</el-button>
			<el-button @click="reset" style="background-color: #37C1D6;border-color: #37C1D6;margin-left: 0;" type="primary"
			 size="small">重置图片</el-button>
			<!-- <div style="font-size: 12px;color: #606266;">小于500KB</div> -->
		</div>

		<div class="upload">
			<input @change="fileChange($event)" type="file" id="upload_file" accept="image/*" multiple style="display: none">
			<div class="upload_warp_img" v-show="imgList.length!=0">
				<div class="upload_warp_img_div" v-for="(item,index) of imgList" :key="index">
					<div class="upload_warp_img_div_top">
						<img src="./img/del.png" class="upload_warp_img_div_del" @click="fileDel(index)">
					</div>
					<el-image style="width: 100px; height: 100px" :src="item.file.src" :preview-src-list="srcList"></el-image>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import $ from 'jquery'
	import Sortable from 'sortablejs'
	import md5 from 'md5';
	export default {
		props: {
			list: {
				type: Array,
				default: () => []
			},
			max: {
				type: Number,
				default: 4
			},
		},
		components: {

		},
		data() {
			return {
				srcList: [],
				imgList: [],
				size: 0,
				sortList: Object,
			};
		},
		watch: {
			imgList: {
				handler: function(newVal) {
					this.srcList = []
					let mSrcList = []
					newVal.forEach((item) => {
						this.srcList.push(item.file.src)
						mSrcList.push(item.file.msrc)
					})
					this.$emit('change', this.srcList,mSrcList);
				},
				deep: true
			},
			list: {
				handler: function(newVal) {
					if (this.list.length != 0) {
						this.list.forEach((item, i) => {
							let file = {
								name: i + 1,
								src: item.src,
								msrc: item.msrc,
							}
							this.imgList.push({
								file
							});
						})

					}
				},
				deep: true
			},
		},
		created() {

		},
		methods: {
			fileClick() {
				document.getElementById('upload_file').click()
			},
			fileChange(el) {
				if (this.imgList.length == this.max || this.imgList.length > this.max){
					this.$message.error('最多只能上传'+this.max + '张图片');
					return
				}
				if (!el.target.files[0].size) return;
				this.fileList(el.target);
				el.target.value = ''
			},
			fileList(fileList) {
				let files = fileList.files;
				let _this = this;
				if (fileList.items !== undefined) { //Chrome拖拽文件
					for (let i = 0; i < fileList.items.length; i++) {
						let item = fileList.items[i];
						if (item.kind === "file" && item.webkitGetAsEntry().isFile) {
							let file = item.getAsFile();
							if (file.size > 5 * 1024 * 1024) {
								this.$message.error('文件尺寸不能超过5M');
								return;
							}
							_this.fileAdd(file);
						} else {
							this.$message.error('不可以上传文件夹');
						}
					}
				} else {
					for (let i = 0; i < files.length; i++) {
						let file = files[i];
						if (file.type != '') { //常规文件判断
							if (file.size > 5 * 1024 * 1024) {
								this.$message.error('文件尺寸不能超过5M');
								return;
							}
							_this.fileAdd(file);
						} else {
							try {
								let fileReader = new FileReader();
								fileReader.readAsDataURL(file.slice(0, 4));
								fileReader.addEventListener('load', function(e) {
									if (file.size > 5 * 1024 * 1024) {
										this.$message.error('文件尺寸不能超过5M');
										return;
									}
									_this.fileAdd(file);
								}, false);
								fileReader.addEventListener('error', function(e) {
									this.$message.error('不可以上传文件夹');
								}, false);
							} catch (e) {
								this.$message.error('不可以上传文件夹');
							}

						}
					}
				}
			},
			//文件添加
			fileAdd(file) {
				//总大小
				this.size = this.size + file.size;
				const form = new FormData();
				form.append('file[]', file);
				this.postImg(form, file)
			},
			postImg(form, file) {
				let env = process.env.NODE_ENV;
				let $domain = '';
				if (env === 'development') {
					// 开发环境路径
					$domain = '/restapi/'
				} else {
					// 生产环境api路径
					$domain = this.$domain
				}

				form.append('timestamp', Math.round(new Date() * 1000))
				form.append('key', localStorage.getItem('token'))
				form.append('port', 'pc')
				form.append('sign', this.getSign(form))

				$.ajax({
					type: "POST",
					url: $domain + '/api/Upimg/UpViceImg',
					dataType: 'json',
					async: false,
					contentType: false,
					processData: false,
					data: form,
					success: (res) => {
						if (res.code == 200) {
							file.src = res.datas[0].vice_img_big
							file.msrc = res.datas[0].vice_img_middle
							this.imgList.push({
								file
							});
							return
						}
					},
					error: (e) => {

					}
				});
			},
			//文件删除
			fileDel(index) {
				this.size = this.size - this.imgList[index].file.size; //总大小
				this.imgList.splice(index, 1);
			},
			//文件大小格式转换
			bytesToSize(bytes) {
				if (bytes === 0) return '0 B';
				let k = 1000, // or 1024
					sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
					i = Math.floor(Math.log(bytes) / Math.log(k));
				return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
			},
			//拖动目标且鼠标进入投放区时触发
			dragenter(el) {
				el.stopPropagation();
				el.preventDefault();
			},
			//拖动目标且鼠标移动在投放区时触发
			dragover(el) {
				el.stopPropagation();
				el.preventDefault();
			},
			//拖动对象且在投放区放开鼠标时触发，要先在dragover上设置禁止默认事件，才会有触发 
			drop(el) {
				el.stopPropagation();
				el.preventDefault();
				this.fileList(el.dataTransfer);
			},
			getSign(data) {
				// 获取签名开始
				let obj = 'jjds2020+';
				let newObj = this.objKeySort(data);
				for (let i in newObj) {
					obj += i + '=' + newObj[i] + '&';
				}
				obj = obj.substring(0, obj.length - 1);
				obj += '+jjds2020';
				obj = md5(obj);
				obj = obj.toUpperCase();
				// 获取签名结束
				return obj
			},
			// 参数排序
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
					newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			},
			reset() {
				this.imgList = []
				this.size = 0
			},
		},
		mounted() {
			var $ul = this.$el.querySelector('.upload_warp_img')
			this.sortList = Sortable.create($ul, {
				handle: '.upload_warp_img_div',
				draggable: ".upload_warp_img_div",
				animation: 150,
				onUpdate: (event) => {
					let newIndex = event.newIndex,
						oldIndex = event.oldIndex
					let $li = $ul.children[newIndex],
						$oldLi = $ul.children[oldIndex]
					// 先删除移动的节点
					$ul.removeChild($li)
					// 再插入移动的节点到原有节点，还原了移动的操作
					if (newIndex > oldIndex) {
						$ul.insertBefore($li, $oldLi)
					} else {
						$ul.insertBefore($li, $oldLi.nextSibling)
					}
					let item = this.imgList[event.oldIndex];
					this.imgList.splice(event.oldIndex, 1);
					this.imgList.splice(event.newIndex, 0, item);
				}
			})
		}
	};
</script>

<style lang="scss">
	.image-drag {
		display: flex;
		width: 800px;
		text-align: center;

		.switch-view {
			padding: 10px 10px;
		}

		.upload {
			border: 1px solid #ebebeb;
			background-color: #fff;
			width: 800px;
			border-radius: 4px;
		}

		.upload_warp {
			margin: 20px;
			padding: 40px;
			border: 1px dashed #d9d9d9;
			border-radius: 4px;
		}

		.upload_warp .txt {
			margin-top: 15px;
			color: #606266;
		}

		.notice {
			margin-left: 20px;
			color: #606266;
		}

		.upload_warp_img_div {
			position: relative;
			height: 100px;
			width: 120px;
			border: 1px solid #666666;
			margin: 0px 32px 10px 0px;
			float: left;
			line-height: 100px;
			display: table-cell;
			text-align: center;
			background-color: #eee;
			cursor: move;
			overflow: hidden;
		}

		.upload_warp_img {
			padding: 24px 0 20px 36px;
			overflow: hidden
		}

		.upload_warp_img_div img {
			max-width: 100%;
			max-height: 100%;
			vertical-align: middle;
		}

		.upload_warp_img_div_top {
			position: absolute;
			top: 0;
			width: 100%;
			height: 30px;
			// background-color: rgba(0, 0, 0, 0.4);
			line-height: 30px;
			text-align: left;
			color: #fff;
			font-size: 12px;
			text-indent: 4px;
			z-index: 9;
		}

		.upload_warp_img_div_del {
			padding: 2px 2px;
			position: absolute;
			top: 2px;
			width: 20px;
			right: 2px;
			cursor: pointer;
			border-radius: 50%;
			background-color: red;
			box-sizing: border-box;
		}
	}
</style>
